<template>
  <div class="orderAdd">
    <div class="btns">
      <div>新增订单</div>
      <div>
        <el-button icon="CircleClose" size="large" @click="doClose(false)">关闭</el-button>
        <el-button type="success" icon="Check" size="large" @click="doSave">保存</el-button>
      </div>
    </div>
    <div class="content">
      <el-card shadow="never">
        <template #header>
          <el-icon color="#ffffff"><Tickets /></el-icon>
          <span class="title">订单信息</span>
        </template>
        <template #default>
          <el-form :model="form" :rules="rules" label-width="85px" size="large" inline ref="formRef" class="order-add-form">
            <el-form-item label="会员:" prop="memberId" required>
              <el-select
                v-model="form.memberId"
                filterable
                remote
                remote-show-suffix 
                clearable 
                placeholder="请输入会员名称查询"
                :remote-method="loadMember"
                @change="loadAddress">
                <el-option v-for="item in members" :key="item.memberId" :label="item.memberName" :value="item.memberId"/>
              </el-select>
            </el-form-item>
            <el-form-item label="厂商:" prop="merchantId" required style="width: 60%;">
              <el-select
                v-model="form.merchantId"
                filterable
                remote
                remote-show-suffix 
                clearable 
                placeholder="请输入厂商名称查询"
                :remote-method="loadFactory"
                @change="factoryChange">
                <el-option v-for="item in factorys" :key="item.merchantId" :label="item.merchantName" :value="item.merchantId"/>
              </el-select>
            </el-form-item>
            <el-form-item label="订单状态:" prop="orderStatus" required>
              <el-select v-model="form.orderStatus" placeholder="请选择订单状态" clearable>
                <el-option label="待付款" :value="0"/>
                <el-option label="待发货" :value="1"/>
                <el-option label="已发货" :value="2"/>
                <el-option label="已完成" :value="3"/>
                <el-option label="已关闭" :value="4"/>
              </el-select>
            </el-form-item>
            <el-form-item label="付款状态:" prop="payStatus" required>
              <el-select v-model="form.payStatus" placeholder="请选择付款状态" clearable>
                <el-option label="未付款" :value="0"/>
                <el-option label="已付款" :value="1"/>
              </el-select>
            </el-form-item>
            <el-form-item label="支付方式:" prop="payType" required>
              <el-select v-model="form.payType" placeholder="请选择支付方式" clearable>
                <el-option label="未支付" :value="0"/>
                <el-option label="支付宝" :value="1"/>
                <el-option label="微信" :value="2"/>
              </el-select>
            </el-form-item>
            <el-form-item label="订单备注:" style="width: 53%;margin-bottom: 0;">
              <el-input v-model="form.note" type="textarea" :rows="4" placeholder="请输入订单备注" clearable></el-input>
            </el-form-item>
          </el-form>
        </template>
      </el-card>
      <el-card shadow="never">
        <template #header>
          <el-icon color="#ffffff"><Guide /></el-icon>
          <span class="title">收货人信息及地址</span>
        </template>
        <template #default>
          <el-form :model="form" label-width="90px" size="large" inline class="order-add-form">
            <el-form-item label="收货人信息:" style="width: 53%;margin-bottom: 0;">
              <el-select v-model="form.receiveId" placeholder="请选择收货人信息" style="width: 100%;">
                <el-option v-for="item in addresses" :key="item.id" :label="item.name + ' / ' + item.phone + ' / ' + item.fullName.replace(/\//g,'')" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-form>
        </template>
      </el-card>
      <el-card shadow="never">
        <template #header>
          <el-icon color="#ffffff"><Goods /></el-icon>
          <span class="title">商品信息</span>
        </template>
        <template #default>
          <el-button type="primary" icon="Plus" size="large" @click="toChooseGoods">选择商品</el-button>
          <el-table :data="form.orderItemList" show-summary border>
            <el-table-column label="商品图片" prop="pic" align="center">
              <template #default="{row}">
                <div class="img-cell">
                  <el-image :src="row.pic + '?x-oss-process=image/resize,m_fill,h_40,w_40'" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="name" header-align="center"></el-table-column>
            <el-table-column label="购买数量" prop="quantity" align="center" width="200">
              <template #default="{row}">
                <el-input-number v-model="row.quantity" :min="1" @change="getTotalPrice(row)" />
              </template>
            </el-table-column>
            <el-table-column label="销售单价" prop="salePrice" align="center"></el-table-column>
            <el-table-column label="促销优惠金额" prop="promotionAmount" align="center"></el-table-column>
            <el-table-column label="点数抵扣金额" prop="pointAmount" align="center"></el-table-column>
            <el-table-column label="优惠券抵扣金额" prop="couponAmount" align="center"></el-table-column>
            <el-table-column label="后台调整折扣金额" prop="discountAmount" align="center">
              <template #default="{row}">
                <el-input v-model="row.discountAmount" type="number" :min="0" @change="getTotalPrice(row)"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="运费" prop="freightAmount" align="center">
              <template #default="{row}">
                <el-input v-model="row.freightAmount" type="number" :min="0" @change="getTotalPrice(row)"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="小计" prop="payAmount" align="center"></el-table-column>
          </el-table>
        </template>
      </el-card>
    </div>

    <!-- 选择商品弹窗 -->
    <el-dialog v-model="show" title="商品选择" top="10vh" width="77%" center draggable>
      <div class="search-box">
        <el-form :model="query" inline>
          <el-form-item label="商品名称:">
            <el-input v-model="query.name" placeholder="请输入商品名称" clearable/>
          </el-form-item>
          <el-form-item label="商品编号:">
            <el-input v-model="query.productCode" placeholder="请输入商品编号" clearable/>
          </el-form-item>
          <el-form-item label="商品分类:">
            <el-select v-model="query.parentCategoryId" placeholder="请选择商品Ⅰ级分类" clearable @change="loadGoodsType" style="margin-right: 10px;">
              <el-option v-for="item in goodTypesOne" :key="item.productCategoryId" :label="item.name" :value="item.productCategoryId"/>
            </el-select>
            <el-select v-model="query.subCategoryId" placeholder="请选择商品Ⅱ级分类" clearable>
              <el-option v-for="item in goodTypesTwo" :key="item.productCategoryId" :label="item.name" :value="item.productCategoryId"/>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="search-btn">
          <el-button icon="Search" color="#16b777" @click="loadGoods(1)">查询</el-button>
          <el-button icon="Plus" color="#FFB800" @click="doChooseGoods">选择</el-button>
          <el-button icon="Refresh" color="#FF5722" @click="resetSearch">重置</el-button>
        </div>
      </div>
      <el-table :data="goodsList" :span-method="tableSpanMethod" max-height="493" ref="tableRef" border>
        <el-table-column type="selection" align="center" width="100" />
        <el-table-column label="商品编号" prop="productCode" align="center" width="180"></el-table-column>
        <el-table-column label="商品名称" prop="productName" header-align="center"></el-table-column>
        <el-table-column label="商品规格" prop="skuName" align="center" header-align="center"></el-table-column>
        <el-table-column label="商品图片" prop="skuPic" align="center">
          <template #default="{row}">
            <div class="img-cell">
              <el-image :src="row.skuPic + '?x-oss-process=image/resize,m_fill,h_40,w_40'" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="价格(元)" prop="salePrice" align="center"></el-table-column>
      </el-table>
      <el-pagination 
        class="paging"
        v-show="query.total"
        small
        layout="total, sizes, prev, pager, next, jumper" 
        :current-page="query.current" 
        :page-size="query.size"
        :total="query.total"
        @current-change="loadGoods"
        @size-change="sizeChange">
      </el-pagination>
    </el-dialog>
  </div>
</template>

<script setup name="orderAdd">
  import { 
    saveOrderApi, 
    getMemberListApi, 
    // getFactoryListApi, 
    getAddressListApi, 
    getGoodsTypeListApi, 
    // getGoodsSkuListPageApi 
  } from '@/api/api'
  import { ref, getCurrentInstance } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties
  const emits = defineEmits(['close'])
  const formRef = ref(null)
  const tableRef = ref(null)

  let show = ref(false)
  let members = ref([])
  let factorys = ref([])
  let addresses = ref([])
  let goodsList = ref([])
  let goodTypesOne = ref([])
  let goodTypesTwo = ref([])
  let rules = ref({
    memberId: [{ required: true, message: '请选择会员', trigger: ['blur', 'change'] }],
    merchantId: [{ required: true, message: '请选择厂商', trigger: ['blur', 'change'] }],
    orderStatus: [{ required: true, message: '请选择订单状态', trigger: ['blur', 'change'] }],
    payStatus: [{ required: true, message: '请选择付款状态', trigger: ['blur', 'change'] }],
    payType: [{ required: true, message: '请选择支付方式', trigger: ['blur', 'change'] }]
  })
  let form = ref({
    memberId: '',
    merchantId: '',
    orderStatus: '',
    payStatus: '',
    payType: '',
    note: '',
    receiveId: '',
    orderItemList: []
  })
  let query = ref({
    merchantId: '',
    name: '',
    productCode: '',
    parentCategoryId: '',
    subCategoryId: '',
    enableStatus: '1',
    current: 1,
    size: 20,
    total: 0
  })

  // 关闭新增
  function doClose(e) {
    emits('close', e)
  }

  // 保存新增
  function doSave() {
    formRef.value.validate((valid) => {
      if (valid) {
        if(form.value.orderItemList.length === 0) {
          currentThis.$message.error('请选择商品')
          return 
        }
        currentThis.$messageBox.confirm(`确认新增吗？`).then(() => {
          let loading = currentThis.$loading(`正在新增`)
          saveOrderApi(form.value).then(res => {
            loading.close()
            if(res.code === '200') {
              doClose(true)
              currentThis.$message.success(res.message)
            } else {
              currentThis.$message.error(res.message)
            }
          })
        }).catch(() => {})
      } else {
        return false;
      }
    })
  }

  // 点击选择商品按钮执行
  function toChooseGoods() {
    if(!form.value.merchantId) {
      currentThis.$message.error('请先选择厂商')
      return
    }
    loadGoods(1)
    show.value = true
  }

  // 执行选择商品
  function doChooseGoods() {
    let chooseGoods = tableRef.value.getSelectionRows()
    if(chooseGoods.length === 0) {
      currentThis.$message.error(`请先勾选商品`)
      return 
    }
    let goodsData = []
    chooseGoods.forEach(item => {
      goodsData.push({
        productId: item.productId,
        skuId: item.skuId,
        name: item.productName,
        pic: item.skuPic,
        quantity: 1,
        salePrice: item.salePrice,
        promotionAmount: 0, // 促销优惠金额
        pointAmount: 0,     // 点数抵扣金额
        couponAmount: 0,    // 优惠券抵扣金额
        discountAmount: 0,  // 后台调整折扣金额
        freightAmount: 0,   // 运费
        usePoint: 0,
        payAmount: item.salePrice   // 应付金额-(小计)
      })
    })
    form.value.orderItemList = goodsData
    show.value = false
  }

  // 查询商品列表
  function loadGoods(page) {
    // query.value.current = page
    // getGoodsSkuListPageApi(query.value).then(res => {
    //   if(res.code === '200') {
    //     let setIndex = 0
    //     let count = 1
    //     let productId = ''
    //     let datas = res.data.pages
    //     // 计算合并行数
    //     datas.forEach((item, index) => {
    //       if(item.productId !== productId) {
    //         productId = item.productId
    //         setIndex = index
    //         count = 1
    //       } else {
    //         count++
    //         datas[setIndex].rowspan = count
    //         datas[index].rowspan = 0
    //       }
    //     })
    //     goodsList.value = datas
    //     query.value.total = res.data.total
    //   } else {
    //     currentThis.$message.error(res.message)
    //   }
    // })
  }

  function sizeChange(size) {
    query.value.size = size
    loadGoods(1)
  }

  // 获取会员下拉选择数据
  function loadMember(member) {
    if(!member) {
      return
    }
    getMemberListApi({member: member}).then(res => {
      if(res.code === '200') {
        members.value = res.data
      }
    })
  }

  // 获取厂商下拉选择数据
  function loadFactory(merchantName) {
    // if(!merchantName) {
    //   return
    // }
    // getFactoryListApi({merchantName: merchantName}).then(res => {
    //   if(res.code === '200') {
    //     factorys.value = res.data
    //   }
    // })
  }

  // 获取收货人信息下拉选择数据
  function loadAddress(memberId) {
    if(!memberId) {
      return
    }
    getAddressListApi(memberId).then(res => {
      if(res.code === '200') {
        addresses.value = res.data
        form.value.receiveId = res.data[0].id
      }
    })
  }

  // 厂商选择改变时执行
  function factoryChange(merchantId) {
    if(!merchantId) {
      return
    }
    query.value.merchantId = merchantId
  }

  /**
   * 查询商品分类下拉列表数据
   * parentId为0或不传时候，查询的是一级商品分类，其他情况查询是二级商品分类
   */
  function loadGoodsType(parentId) {
    if(!parentId) {
      goodTypesTwo.value = []
      query.value.subCategoryId = ''
      return
    }
    getGoodsTypeListApi({parentId: parentId}).then(res => {
      if(res.code === '200') {
        if(parentId === '0') {
          goodTypesOne.value = res.data
        } else {
          goodTypesTwo.value = res.data
          query.value.subCategoryId = ''
        }
      }
    })
  }
  loadGoodsType('0') // 初始商品分类的一级分类

  // 重置查询商品列表参数
  function resetSearch() {
    query.value.name = ''
    query.value.productCode = ''
    query.value.parentCategoryId = ''
    query.value.subCategoryId = ''
    loadGoods(1)
  }

  // 合并商品编号
  function tableSpanMethod({row, column, rowIndex, columnIndex}) {
    if(columnIndex === 1) {
      if(row.rowspan !== 0) {
        return {rowspan: row.rowspan, colspan: 1}
      } else {
        return {rowspan: 0, colspan: 0}
      }
    }
  }

  // 计算小计
  function getTotalPrice(e) {
    e.payAmount = e.quantity * e.salePrice - e.promotionAmount - e.pointAmount - e.couponAmount - parseFloat(e.discountAmount) + parseFloat(e.freightAmount)
  }
</script>

<style lang="less" scoped>
.orderAdd{
  padding: 0 80px;
  .btns{
    height: 8vh;
    display: flex;
    justify-content: space-between;
    align-items: center;
    >div{
      width: 50%;
      &:first-child{
        font-size: 25px;
        font-weight: bold;
      }
      &:last-child{
        display: flex;
        justify-content: flex-end;
      }
    }
  }
  .content{
    height: 92vh;
    overflow: hidden auto;
    :deep(.el-card){
      margin-bottom: 15px;
      .el-card__header{
        display: flex;
        align-items: center;
        background: #3BB9F1;
        .el-icon{
          margin-right: 5px;
        }
        .title{
          color: #ffffff;
        }
      }
      .el-card__body{
        .order-add-form.el-form{
          .el-form-item {
            width: 30%;
          }
        }
        .el-table{
          margin-top: 10px;
          .img-cell{
            display: flex;
            justify-content: center;
            align-items: center;
            .el-image{
              width: 40px; 
              height: 40px;
              border-radius: 5px;
            }
          }
        }
      }
    }
  }
  :deep(.el-dialog){
    .search-box{
      display: flex;
      justify-content: space-between;
      .el-input{
        width: 190px;
      }
      >.search-btn{
        text-align: right;
        >.el-button{
          color: #ffffff !important;
        }
      }
    }
    .img-cell{
      display: flex;
      justify-content: center;
      align-items: center;
      .el-image{
        width: 40px; 
        height: 40px;
        border-radius: 5px;
      }
    }
  }
}
</style>